﻿namespace FolderSync
{
    using System;
    using System.Linq;
    public class MirrorSerializer
    {
        public ConfigurationSet[] configsets { get; set; }
        public INotifier Notifier { get; set; }
        public Syncer Syncer { get; set; }
        private Mirrorer _mirrorer;
        private bool _treadRunning;
        public delegate void StatusChangedHandler(object sender, string status);
        public event StatusChangedHandler StatusChanged;
        void mirrorer_StatusChanged(Mirrorer sender, string status)
        {
            if (StatusChanged != null) StatusChanged(sender, status);
        }
        public void Stop()
        {
            _treadRunning = false;
            if (_mirrorer != null) _mirrorer.Stop();
        }
        public void Run()
        {
            _treadRunning = true;
            foreach (var configset in configsets)
            {
                if (_treadRunning)
                {

                    if (configset.Merge)
                    {
                        _mirrorer = new Mirrorer()
                        {
                            Notifier = Notifier,
                            filter = new RegExpFileFilter()
                            {
                                rd = configset.IncludeDirectory,
                                rf = configset.IncludeFile,
                                xd = configset.ExcludeDirectory,
                                xf = configset.ExcludeFile
                            },
                            TranslatePath = (s => s.Replace(configset.Source, configset.Destination)),
                            ReverseTranslatePath = (s => s.Replace(configset.Destination, configset.Source)),
                            Destructive = configset.Mirror,
                            Syncer = Syncer,
                            WatchFolderName = configset.Source,
                            LogTag=configset.Name
                        };
                        _mirrorer.StatusChanged += new FolderSync.Mirrorer.StatusChangedHandler(mirrorer_StatusChanged);
                        _mirrorer.Run();
                        _mirrorer=null;
                    }
                }
                _treadRunning = false;
            }
        }
        public bool AnyRunning { get { return _treadRunning; } }
        public string Status
        {
            get
            {
                return _treadRunning
                    ? "MirrorSerializer is running: " + _mirrorer.Status
                    : "MirrorSerializer is not running";
            }
        }
    }
}